/**
 * 
 */
package br.com.cnpv.modelo.bo;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.cnpv.modelo.acesso.idao.IFotoVistoriaEventoDAO;
import br.com.cnpv.modelo.acesso.idao.IVistoriaEventoDAO;
import br.com.cnpv.modelo.dao.FotoVistoriaEventoDAO;
import br.com.cnpv.modelo.dao.VistoriaEventoDAO;
import br.com.cnpv.modelo.entity.FotoVistoriaEvento;
import br.com.cnpv.modelo.entity.Usuario;
import br.com.cnpv.modelo.entity.VistoriaEvento;
import br.com.cnpv.util.HibernateUtil;

/**
 * @author ricardo
 *
 */
public class VistoriaBO extends HibernateUtil {

	public static VistoriaBO INSTANCE;
	
	public static VistoriaBO getInstance()
	{
		if(INSTANCE == null)
		{
			synchronized (VistoriaBO.class) {
				INSTANCE = new VistoriaBO();
			}
		}
		return INSTANCE;
	}

	public List<VistoriaEvento> listar(Integer idAssociacao, String tipo) throws Exception
	{
		Session session = null;
		List<VistoriaEvento> list = null;
		try
		{
			session = currentSession();
			IVistoriaEventoDAO dao = new VistoriaEventoDAO();
			list = dao.listar(idAssociacao, tipo, session);
		}catch(Exception e)
		{
			throw new Exception(e);
		}finally
		{
			if(session != null)
			{
				session.flush();
				session.clear();
			}
			closeSession();
		}
		return list;
	}

	public void saveOrUpdate(VistoriaEvento vistoriaEvento, List<byte[]> imagemList, Usuario usuario) throws Exception 
	{
		Session session = null;
		Transaction transaction = null;
		
		try
		{
			session = currentSession();
			transaction = session.beginTransaction();
			
			vistoriaEvento.setIdTipoVistoria(3);
			
			IVistoriaEventoDAO vistoriaEventoDao = new VistoriaEventoDAO();
			vistoriaEventoDao.saveOrUpdate(vistoriaEvento, session);
			
			IFotoVistoriaEventoDAO fotoVistoriaEventoDao = new FotoVistoriaEventoDAO();
			
			for(byte[] img : imagemList)
			{
				FotoVistoriaEvento fotoVistoriaEvento = new FotoVistoriaEvento();
				fotoVistoriaEvento.setIdVistoria(vistoriaEvento.getId());
				fotoVistoriaEvento.setArqFotoVistoria(img);
				fotoVistoriaEvento.setIdUsuario(usuario.getId());
				fotoVistoriaEvento.setDtIncl(new Date());
				fotoVistoriaEventoDao.saveOrUpdate(fotoVistoriaEvento, session);
			}
			
			transaction.commit();
		}catch(Exception e)
		{
			transaction.rollback();
			throw new Exception(e);
		}finally
		{
			if(session != null)
			{
				session.flush();
				session.clear();
			}
			closeSession();
		}
		
	}
}